@{
    ViewData["Title"] = "采购入库";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>@ViewData["Title"]</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="~/layui/css/layui.css">
</head>
<body>
    <div class="layui-container" style="padding: 20px;">
        <form class="layui-form" lay-filter="mainForm">
            <input type="hidden" name="id" id="id" value="@ViewBag.Id">
            
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>入库单编号</label>
                        <div class="layui-input-block">
                            <div class="layui-input-group">
                                <input type="text" name="lnboundCode" placeholder="请输入入库单编号" class="layui-input" lay-verify="required">
                                <div class="layui-input-split layui-input-suffix" style="cursor: pointer;" id="btnGenerateCode">
                                    <i class="layui-icon layui-icon-refresh"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>入库单名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="lnboundName" placeholder="请输入入库单名称" class="layui-input" lay-verify="required">
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-row layui-col-space10">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>供应商</label>
                        <div class="layui-input-block">
                            <div class="layui-input-group">
                                <input type="text" name="vendor" placeholder="请选择供应商" class="layui-input" lay-verify="required" readonly>
                                <div class="layui-input-split layui-input-suffix" style="cursor: pointer;" id="btnSelectSupplier">
                                    <i class="layui-icon layui-icon-search"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>入库日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="lnboundDate" placeholder="请选择入库日期" class="layui-input" lay-verify="required" id="lnboundDate">
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-row layui-col-space10">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">采购订单号</label>
                        <div class="layui-input-block">
                            <input type="text" name="procurementNumber" placeholder="请输入采购订单号" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red;">*</span>入库仓库</label>
                        <div class="layui-input-block">
                            <select name="lnboundWarehous" lay-verify="required" lay-search="">
                                <option value="">请选择仓库</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">总金额</label>
                <div class="layui-input-block" style="width: 200px;">
                    <input type="number" name="totalAmount" placeholder="请输入总金额" class="layui-input" step="0.01">
                </div>
            </div>

            <!-- 入库明细部分（仅编辑时显示） -->
            <div id="detailSection" style="display: none;">
                <fieldset class="layui-elem-field layui-field-title">
                    <legend>入库明细</legend>
                </fieldset>
                
                <div class="layui-form-item">
                    <button type="button" class="layui-btn layui-btn-sm" id="btnAddDetail">
                        <i class="layui-icon layui-icon-add-1"></i> 添加明细
                    </button>
                </div>

                <table class="layui-hide" id="detailTable" lay-filter="detailTable"></table>
            </div>

            <div class="layui-form-item" style="margin-top: 30px;">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="save">保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="parent.layer.closeAll()">取消</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 明细操作列模板 -->
    <script type="text/html" id="detailToolbarTpl">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete" title="删除">
            <i class="layui-icon layui-icon-delete"></i>
        </a>
    </script>

    <script src="~/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer', 'laydate', 'table'], function () {
            var $ = layui.jquery;
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var table = layui.table;

            var isEdit = '@ViewBag.Id' !== '';
            var procurementId = '@ViewBag.Id' || 0;

            // 初始化日期选择器
            laydate.render({
                elem: '#lnboundDate',
                type: 'datetime'
            });

            // 加载仓库选择列表
            loadWarehouses();

            // 生成编号按钮
            $('#btnGenerateCode').on('click', function() {
                $.get('/Procurement/GenerateInboundCode', function (result) {
                    if (result.success) {
                        $('input[name="lnboundCode"]').val(result.code);
                    }
                });
            });

            // 选择供应商按钮
            $('#btnSelectSupplier').on('click', function() {
                layer.open({
                    type: 2,
                    title: '选择供应商',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['1000px', '700px'],
                    content: '/Procurement/SupplierSelect'
                });
            });

            // 供应商选择回调函数
            window.selectSupplierCallback = function(supplier) {
                $('input[name="vendor"]').val(supplier.supplierName);
            };

            // 加载仓库列表
            function loadWarehouses() {
                $.get('/Procurement/GetWarehouseSelect', function(result) {
                    if (result.success) {
                        var options = '<option value="">请选择仓库</option>';
                        result.data.forEach(function(item) {
                            options += `<option value="${item.warehouseName}">${item.warehouseName}</option>`;
                        });
                        $('select[name="lnboundWarehous"]').html(options);
                        form.render('select');
                    }
                });
            }

            // 加载仓库列表到明细表单
            function loadWarehousesForDetail(layero) {
                $.get('/Procurement/GetWarehouseSelect', function(result) {
                    if (result.success) {
                        var options = '<option value="">请选择仓库</option>';
                        result.data.forEach(function(item) {
                            options += `<option value="${item.id}">${item.warehouseName}</option>`;
                        });
                        layero.find('select[name="warehouseId"]').html(options);
                        form.render('select');
                    }
                });
            }

            // 保存表单
            form.on('submit(save)', function (data) {
                var field = data.field;
                
                // 处理总金额字段，如果为空则设置为空字符串
                if (!field.totalAmount || field.totalAmount.trim() === '') {
                    field.totalAmount = '';
                }
                
                // 调试：打印提交的数据
                console.log('提交的表单数据:', field);
                
                var url = isEdit ? '/Procurement/UpdateProcurement' : '/Procurement/CreateProcurement';
                
                $.post(url, field, function (result) {
                    if (result.success) {
                        layer.msg('保存成功');
                        setTimeout(function () {
                            parent.layer.closeAll();
                        }, 1000);
                    } else {
                        console.error('保存失败:', result);
                        layer.msg(result.message || '保存失败');
                    }
                }).fail(function(xhr, status, error) {
                    console.error('请求失败:', xhr.responseText);
                    layer.msg('请求失败: ' + error);
                });
                return false;
            });

            // 如果是编辑模式，加载数据并显示明细
            if (isEdit) {
                $('#detailSection').show();
                initDetailTable();
                
                $.get('/Procurement/GetProcurement', { id: procurementId }, function(result) {
                    if (result.success) {
                        var data = result.data;
                        form.val('mainForm', {
                            'id': data.id,
                            'lnboundCode': data.lnboundCode,
                            'lnboundName': data.lnboundName,
                            'vendor': data.vendor,
                            'lnboundDate': formatDateTime(new Date(data.lnboundDate)),
                            'procurementNumber': data.procurementNumber,
                            'lnboundWarehous': data.lnboundWarehous,
                            'totalAmount': data.totalAmount
                        });
                    }
                });
            } else {
                // 新增模式，生成编号并设置默认日期
                $.get('/Procurement/GenerateInboundCode', function (result) {
                    if (result.success) {
                        $('input[name="lnboundCode"]').val(result.code);
                    }
                });
                $('input[name="lnboundDate"]').val(formatDateTime(new Date()));
            }

            // 初始化明细表格
            function initDetailTable() {
                window.detailTableIns = table.render({
                    elem: '#detailTable',
                    url: '/Procurement/GetDetails',
                    where: { procurementId: procurementId },
                    cols: [[
                        { field: 'materialCode', title: '物料编码', width: 120 },
                        { field: 'materialName', title: '物料名称', width: 150 },
                        { field: 'specifications', title: '规格型号', width: 120 },
                        { field: 'inputNum', title: '入库数量', width: 100 },
                        { field: 'unit', title: '单位', width: 80 },
                        { field: 'money', title: '金额', width: 100 },
                        { field: 'batch', title: '批次', width: 100 },
                        { field: 'warehouseName', title: '仓库', width: 100 },
                        { field: 'desc', title: '描述', width: 150 },
                        { fixed: 'right', title: '操作', toolbar: '#detailToolbarTpl', width: 80 }
                    ]],
                    page: false,
                    height: 300
                });

                // 明细表格工具栏事件
                table.on('tool(detailTable)', function(obj) {
                    var data = obj.data;
                    if (obj.event === 'delete') {
                        layer.confirm('确定删除这条明细吗？', function(index) {
                            $.post('/Procurement/DeleteDetail', { detailId: data.id }, function(result) {
                                if (result.success) {
                                    layer.msg('删除成功');
                                    window.detailTableIns.reload();
                                } else {
                                    layer.msg(result.message || '删除失败');
                                }
                            });
                            layer.close(index);
                        });
                    }
                });
            }

            // 添加明细按钮
            $('#btnAddDetail').on('click', function() {
                layer.open({
                    type: 1,
                    title: '添加入库明细',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['800px', '600px'],
                    content: getDetailFormHtml(),
                    success: function(layero, index) {
                        initDetailForm(layero, index);
                    }
                });
            });

            // 获取明细表单HTML
            function getDetailFormHtml() {
                return `
                    <div style="padding: 20px;">
                        <form class="layui-form" lay-filter="detailForm">
                            <input type="hidden" name="procurementId" value="${procurementId}">
                            <input type="hidden" name="materialId">
                            
                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">物料编码</label>
                                        <div class="layui-input-block">
                                            <div class="layui-input-group">
                                                <input type="text" name="materialCode" placeholder="请选择物料" class="layui-input" readonly lay-verify="required">
                                                <div class="layui-input-split layui-input-suffix" style="cursor: pointer;" id="btnSelectMaterial">
                                                    <i class="layui-icon layui-icon-search"></i>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">物料名称</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="materialName" placeholder="物料名称" class="layui-input" readonly>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">规格型号</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="specifications" placeholder="规格型号" class="layui-input" readonly>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">单位</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="unit" placeholder="单位" class="layui-input" readonly>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">入库数量</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="inputNum" placeholder="请输入数量" class="layui-input" lay-verify="required">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">金额</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="money" placeholder="请输入金额" class="layui-input" step="0.01">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">批次</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="batch" placeholder="请输入批次" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">仓库</label>
                                        <div class="layui-input-block">
                                            <select name="warehouseId" lay-verify="required" lay-search="">
                                                <option value="">请选择仓库</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">描述</label>
                                <div class="layui-input-block">
                                    <textarea name="desc" placeholder="请输入描述" class="layui-textarea"></textarea>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="saveDetail">保存</button>
                                    <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                                </div>
                            </div>
                        </form>
                    </div>
                `;
            }

            // 初始化明细表单
            function initDetailForm(layero, index) {
                // 重新渲染表单
                form.render();
                
                // 加载仓库列表到明细表单
                loadWarehousesForDetail(layero);
                
                // 选择物料按钮
                layero.find('#btnSelectMaterial').on('click', function() {
                    layer.open({
                        type: 2,
                        title: '选择物料',
                        shadeClose: true,
                        shade: 0.8,
                        area: ['1600px', '900px'],
                        content: '/Procurement/MaterialSelect'
                    });
                });

                // 物料选择回调函数
                window.selectMaterialCallback = function(material) {
                    layero.find('input[name="materialCode"]').val(material.materielCode);
                    layero.find('input[name="materialId"]').val(material.id);
                    // 同时填充其他相关字段
                    layero.find('input[name="materialName"]').val(material.materielName);
                    layero.find('input[name="specifications"]').val(material.specifications);
                    layero.find('input[name="unit"]').val(material.unit);
                };

                // 保存明细
                form.on('submit(saveDetail)', function(data) {
                    var field = data.field;
                    
                    // 验证必填字段
                    if (!field.materialId) {
                        layer.msg('请选择物料');
                        return false;
                    }
                    if (!field.inputNum || field.inputNum <= 0) {
                        layer.msg('请输入正确的入库数量');
                        return false;
                    }
                    if (!field.warehouseId) {
                        layer.msg('请选择仓库');
                        return false;
                    }
                    
                    // 设置入库日期为当前日期
                    field.inDate = new Date().toISOString();
                    
                    $.post('/Procurement/AddDetail', field, function(result) {
                        if (result.success) {
                            layer.msg('添加成功');
                            layer.close(index);
                            // 重新加载明细表格
                            if (window.detailTableIns) {
                                window.detailTableIns.reload();
                            }
                        } else {
                            layer.msg(result.message || '添加失败');
                        }
                    }).fail(function() {
                        layer.msg('网络错误，请稍后重试');
                    });
                    return false;
                });
            }

            // 格式化日期时间
            function formatDateTime(date) {
                return date.getFullYear() + '-' +
                    ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
                    ('0' + date.getDate()).slice(-2) + ' ' +
                    ('0' + date.getHours()).slice(-2) + ':' +
                    ('0' + date.getMinutes()).slice(-2) + ':' +
                    ('0' + date.getSeconds()).slice(-2);
            }
        });
    </script>
</body>
</html> 